# ruby_fetion/shell.rb
# -*- encoding: utf-8 -*-
# License: GPL v2
# Author:  jhsea3do@gmail.com
# Version: 0.1

require 'readline'
require 'highline/import'

logger = $logger || Logger.new(STDOUT)
q_flag = false
l_flag = false
t_noop = 5
fetionno = $fetionno
password = $password
if fetionno.nil? || password.nil?
  fetionno = Readline.readline('>> fetionno? ') if fetionno.nil?
  STDOUT << '>> password? '; STDOUT.flush
  password = ask('') {|q|q.echo='*'}
end
fc = FetionClient.new :mobileno => fetionno.strip, :password => password.strip, :logger => logger
th = Thread.new do
begin
  fc.login
  fc.get_contact_list
  fc.get_contacts_info
  fc.get_offline_messages
  l_flag = true
  while true
    break if q_flag
    fc.read_notify
    fc.keep_alive
    sleep t_noop
  end
rescue
  # quit
  q_flag = true
  STDOUT << " fatal #{$!}"; STDOUT.flush
end
end
l_wait = 0
while true
  break if l_flag
  break if q_flag
  STDOUT << '-'
  STDOUT.flush
  sleep 1
  l_wait += 1
  q_flag = true if l_wait > 30
end
STDOUT << "> ready to go!" if !q_flag
puts ''
while true
  break if q_flag
  input = Readline.readline('$ ')
  if 'quit' == input || 'exit' == input
    q_flag = true
    break if q_flag
  elsif 'info' == input
    fc.get_contact_list
  elsif 'search' == input
    arr = fc.get_contacts /13816744731/ 
    puts arr.first.first
  elsif 'send' == input
    mobileno = Readline.readline('>> mobile? ')
    sms_text = Readline.readline('>> content? ')
    mobileno = false if mobileno.match(FetionClient::FETION_MOBILE_EXPR).nil?
    fc.send_sms sms_text, mobileno
  elsif 'follow' == input
    mobileno = Readline.readline('>> mobile? ')
    fc.follow mobileno
  end
end
# fc.send_sms('test -中文-')
# th.join
fc.logout if l_flag
